<template>
  <!-- 使用卡片布局 -->
  <el-card class="box-card">
    <template #header>添加账号</template>

    <!-- 表单 -->
    <el-form
      :model="accountForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-form-item label="账号" prop="account">
        <el-input
          type="text"
          v-model="accountForm.account"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="accountForm.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户组" prop="userGroup">
        <el-select v-model="accountForm.userGroup" placeholder="请选择">
          <el-option label="超级管理员" value="超级管理员"> </el-option>
          <el-option label="普通管理员" value="普通管理员"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import {
  validateAccount,
  validatePass,
  validateGroup
} from '@/utils/validate.js'
import { addAccount } from '@/api/users.js'

export default {
  data() {
    return {
      // 数据对象
      accountForm: {
        account: '',
        password: '',
        userGroup: ''
      },
      // 规则对象
      rules: {
        account: [{ validator: validateAccount, trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }],
        userGroup: [{ validator: validateGroup, trigger: 'change' }]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 表单校验完成，可以发请求了
          const { code } = await addAccount(this.accountForm)
          if (code === 0) {
            setTimeout(() => {
              this.$router.push('/account/list')
            }, 1500)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 370px;

  .el-input {
    width: 178px;
  }
}
</style>
